package com.sgb.kjwl.view.ui.fragment.manage

import android.app.Dialog
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.scwang.smart.refresh.layout.listener.ScrollBoundaryDecider
import com.sgb.capital.view.widget.MToast
import com.sgb.kjwl.AppLazyFragment
import com.sgb.kjwl.R
import com.sgb.kjwl.databinding.FragmentAgentStaffCheckBinding
import com.sgb.kjwl.databinding.ItemAgentStaffCheckBinding
import com.sgb.kjwl.di.self.DaggerSelfFragComponent
import com.sgb.kjwl.di.self.SelfFragModule
import com.sgb.kjwl.model.entity.manage.AgentStaffCheckEntity
import com.swgk.core.event.EventConstant
import com.sgb.kjwl.view.event.self.AgentApplyEvent
import com.sgb.kjwl.view.ui.activity.manage.AgentStaffCheckAddActivity
import com.sgb.kjwl.view.ui.activity.manage.AgentStaffCheckDetailActivity
import com.sgb.link.view.widget.InputDialog
import com.sgb.kjwl.viewmodel.manage.AgentCheckModel
import com.swgk.core.base.di.AppComponent
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration
import com.im.immodel.IMUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import javax.inject.Inject

class AgentStaffCheckFragment : AppLazyFragment() {

    private lateinit var mBinding : FragmentAgentStaffCheckBinding

    private var isLoadMore = false // 是否是加载更多
    private var isEnableLoadMore = false //是否可以上拉加载

    @Inject
    lateinit var mModel : AgentCheckModel

    private lateinit var mAdapter : AgentStaffCheckAdapter

    private var mRefuseDialog : InputDialog?= null
    private var mRefusePosition : Int = -1

    companion object{
        const val TAG = "agentStaffCheckFragment"

        fun newInstance()  : AgentStaffCheckFragment{
            val fragment = AgentStaffCheckFragment()
            val bundle = Bundle()
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun setupFragmentComponent(appComponent: AppComponent?) {
        super.setupFragmentComponent(appComponent)
        DaggerSelfFragComponent.builder().appComponent(appComponent)
            .selfFragModule(SelfFragModule()).build().inject(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_agent_staff_check, container, false)
        return mBinding.root
    }

    override fun initView() {
        super.initView()
        mBinding.recycleView.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
        // SwipeRefreshLayout 刷新
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                isLoadMore = true
                refreshDatas()
                mBinding.refreshLayout.finishLoadMore(500)
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                isLoadMore = false
                refreshDatas()
                mBinding.refreshLayout.finishRefresh(500)
            }
        })
        //解决 在实现 上拉加载更多 和 下拉刷新 时  遇到item不在顶端就执行了刷新的方法和数据item没有填满屏幕也执行了加载更多
        mBinding.refreshLayout.setScrollBoundaryDecider(object : ScrollBoundaryDecider {
            override fun canRefresh(content: View): Boolean {
                if (mBinding.recycleView == null) return false
                return mBinding.recycleView.computeVerticalScrollOffset() === 0
            }

            override fun canLoadMore(content: View): Boolean {
                if (mBinding.recycleView == null) return false
                //整个View控件的高度
                val scrollRange: Int = mBinding.recycleView.computeVerticalScrollRange()
                //当前屏幕之前滑过的距离
                val scrollOffset: Int = mBinding.recycleView.computeVerticalScrollOffset()
                //当前屏幕显示的区域高度
                val scrollExtent: Int = mBinding.recycleView.computeVerticalScrollExtent()
                //获取recyclerView的高度
                val height: Int = mBinding.recycleView.height
                if (height > scrollRange) {
                    return false
                }
                return isEnableLoadMore && scrollRange <= scrollOffset + scrollExtent
            }
        })
        mAdapter = AgentStaffCheckAdapter(R.layout.item_agent_staff_check)
        mAdapter.bindToRecyclerView(mBinding.recycleView)
        val empty = LayoutInflater.from(context).inflate(R.layout.layout_empty_view, mBinding.recycleView, false)
        mAdapter.emptyView = empty
        mAdapter.setCallBack(object : ClickCallBack{
            override fun clickAgree(item: AgentStaffCheckEntity?, position: Int) {
                if (item != null){
                   //AgentStaffCheckDetailActivity.launch(context!!, item)
                    //同意 添加成员页面
                    AgentStaffCheckAddActivity.launch(context!!, item)
                }
            }

            override fun clickRefuse(item: AgentStaffCheckEntity?, position: Int) {
                 if (item != null){
                     //拒绝加入
                     showRefuseDialog(item.id, position)
                 }
            }

            override fun goToChat(item: AgentStaffCheckEntity?, position: Int) {
                if (item != null){
                    //去聊天
                    mModel.getImAccount(item.userNo, "0")
                }
            }

            override fun clickItem(item: AgentStaffCheckEntity?) {
                if (item != null){
                    AgentStaffCheckDetailActivity.launch(context!!, item)
                }
            }

        })
        mBinding.recycleView.addItemDecoration(
            RecyclerCustomDecoration(
                0f,
                0f,
                0f,
                resources.getDimension(R.dimen.dp10), resources.getColor(R.color.color_main_bg)
            )
        )

        mModel.staffCheckList.observe(this, {
            isEnableLoadMore = it.size >= 10
            if (isLoadMore){
                mAdapter.addData(it)
            } else {
                mAdapter.setNewData(it)
            }
        })
        mModel.rejectSuccess.observe(this, {
            if (!TextUtils.isEmpty(it)) {
                MToast.showToast(context, it)
                mModel.rejectSuccess.postValue("")
                if (mRefusePosition != -1){
                    mAdapter.remove(mRefusePosition)
                    mRefusePosition = -1
                }
            }

        })
        mModel.mImMsg.observe(this, {
            if (it != null){
                if (TextUtils.isEmpty(it.imAccount)){
                    Toast.makeText(context, "im账号不能为空！！", Toast.LENGTH_SHORT).show()
                    return@observe
                }
                IMUtils.getInstance().buildSingleTalking(it.imAccount)
            }
        })
    }

    //刷新/加载数据
    private fun refreshDatas() {
        mModel.getStaffCheckList(requireContext(), isLoadMore)
    }

    override fun onLazyLoad() {
        isLoadMore = false
        refreshDatas()
    }

    private fun showRefuseDialog(id : String, position: Int) {
        if (mRefuseDialog == null){
            mRefuseDialog = InputDialog(activity).builder().setNegativeButton("").setPositiveButton("")
                .setEtHint("填写拒绝理由（必填）").setCancelable(false)
                .setDialogCallBack(object : InputDialog.DialogCallBack{
                    override fun onRightClick(content: String?, dialog : Dialog) {
                        if (TextUtils.isEmpty(content)){
                            MToast.showToast(activity,  "请输入拒绝理由")
                        } else {
                            //请求拒绝接口
                            goToRefuse(content!!, id)
                            mRefusePosition = position
                            mRefuseDialog!!.reset()
                            dialog.dismiss()
                        }
                    }

                    override fun onLeftClick() {

                    }

                })
        }
        mRefuseDialog!!.show()
    }

    private fun goToRefuse(content: String, id: String) {
        mModel.rejectAdd(requireContext(), content, id)
    }


    class AgentStaffCheckAdapter(layoutResId : Int) : BaseQuickAdapter<AgentStaffCheckEntity, BaseViewHolder>(layoutResId){
        private  var mItemBinging : ItemAgentStaffCheckBinding?= null
        private var mCallBack : ClickCallBack ?= null

        public fun setCallBack(callBack : ClickCallBack){
            this.mCallBack = callBack
        }

        override fun convert(helper: BaseViewHolder?, item: AgentStaffCheckEntity?) {
            mItemBinging = DataBindingUtil.bind(helper!!.itemView)
            if (mItemBinging != null) {
                mItemBinging!!.viewModel = item
                mItemBinging!!.executePendingBindings()
                Glide.with(mContext).load(item!!.image).apply(
                    RequestOptions()
                        .placeholder(R.mipmap.def_photo)
                        .fallback(R.mipmap.def_photo)
                        .error(R.mipmap.def_photo)
                ).into(mItemBinging!!.ivUser)
                mItemBinging!!.tvAgree.setOnClickListener {
                    if (mCallBack != null){
                        mCallBack!!.clickAgree(item, helper.layoutPosition)
                    }
                }
                mItemBinging!!.tvRefuse.setOnClickListener {
                    if (mCallBack != null){
                        mCallBack!!.clickRefuse(item, helper.layoutPosition)
                    }
                }
                mItemBinging!!.root.setOnClickListener {
                    if (mCallBack != null){
                        mCallBack!!.clickItem(item)
                    }
                }
                mItemBinging!!.tvChat.setOnClickListener {
                    if (mCallBack != null){
                        mCallBack!!.goToChat(item, helper.layoutPosition)
                    }
                }
            }
        }
    }

    interface ClickCallBack{
       fun clickAgree(item: AgentStaffCheckEntity?, position : Int)
       fun clickRefuse(item: AgentStaffCheckEntity?, position : Int)
       fun goToChat(item: AgentStaffCheckEntity?, position : Int)
       fun clickItem(item: AgentStaffCheckEntity?)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(event : AgentApplyEvent){
        if (event.messageTag == EventConstant.EVENT_AGENT_APPLY_REJECT || event.messageTag == EventConstant.EVENT_AGENT_APPLY_SUCCESS){
            isLoadMore = false
            refreshDatas()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}